using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SharedKernel.Infrastructure.Caches;
using SharedKernel.Infrastructure.Redis;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 缓存依赖注入扩展
    /// </summary>
    public static class CacheDependencyInjection
    {
        /// <summary>
        /// 添加缓存服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <param name="sectionName">配置节名称</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddCache(this IServiceCollection services, IConfiguration configuration, string sectionName = "")
        { 
            services.AddMemoryCache();//添加内存缓存
            //注入Redis缓存
            if (!string.IsNullOrWhiteSpace(sectionName))
            {
                var redisOptions = configuration.GetSection(sectionName).Get<RedisOptions>();

                if (redisOptions != null)
                {
                    services.Configure<RedisOptions>(options =>
                    {
                        options.ConnectionString = redisOptions.ConnectionString;
                        options.ConnectTimeout = redisOptions.ConnectTimeout;
                        options.Password = redisOptions.Password;
                        options.Ssl = redisOptions.Ssl;
                        options.DefaultDatabase = redisOptions.DefaultDatabase;
                        options.SyncTimeout = redisOptions.DefaultDatabase;
                    }); 
                    // 注册Redis缓存
                    services.AddSingleton<RedisCacheService>(provider =>
                    {
                        var options = provider.GetRequiredService<IOptions<RedisOptions>>();
                        var logger = provider.GetRequiredService<ILogger<RedisCacheService>>();
                        return new RedisCacheService(options, services);
                    });

                    // 注册缓存工厂
                    services.AddSingleton<ICacheService, CacheServiceFactory>();
                }
            }
            return services;
        }
    }
}